﻿using LikeBangumi.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Text.RegularExpressions;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Web.Http;
using Newtonsoft.Json;
using System.Collections.ObjectModel;

// “空白页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234238 上有介绍

namespace LikeBangumi.Pages
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class DiliPage : Page
    {
        public DiliPage()
        {
            this.InitializeComponent();
            NavigationCacheMode = NavigationCacheMode.Required;
          
        }
        public delegate void PageChnage(BangumiType type, string sid);
        public event PageChnage PageChnageEvent;
        public event PageChnage PlayEvent;
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.NavigationMode == NavigationMode.New)
            {
                if (list_Video.Items.Count == 0)
                {
                    pivot.SelectedIndex = 1;
                   // GetDiliHome();
                    TypeLoad();

                }
            }
          
        }

        private void TypeLoad()
        {
            List<CbTypeModel> list_Date = new List<CbTypeModel>();
            for (int i = 2010; i <= 2016; i++)
            {
                int num = 1;
                for (int j = 0; j < 4; j++)
                {
                    if (DateTime.Now>new DateTime(i,num,1))
                    {
                        list_Date.Add(new CbTypeModel() { Name = i + "年" + num + "月", Info = "http://www.dilidili.com/anime/" + i.ToString() + num.ToString("00")+"/" });
                        num += 3;
                    }
                }
            }
            cb_Date.ItemsSource = list_Date.OrderByDescending(x=>x.Info);
            List<CbTypeModel> list_Area = new List<CbTypeModel>() {
                new CbTypeModel() {Name="日本",Info="http://www.dilidili.com/riyu/"},
                 new CbTypeModel() {Name="中国",Info="http://www.dilidili.com/guoyu/"},
                  new CbTypeModel() {Name="欧美",Info="http://www.dilidili.com/yingyu/"},
                   new CbTypeModel() {Name="港台",Info="http://www.dilidili.com/yueyu/"}
            };
            cb_Area.ItemsSource = list_Area;
            List<CbTypeModel> list_Type = new List<CbTypeModel>();
            string a = @"<dd><a href=""http://www.dilidili.com/gaoxiao/"">搞笑</a><a href=""http://www.dilidili.com/kehuan/"">科幻</a><a href=""http://www.dilidili.com/yundong/"">运动</a><a href=""http://www.dilidili.com/danmei/"">耽美</a><a href=""http://www.dilidili.com/zhiyuxi/"">治愈系</a><a href=""http://www.dilidili.com/luoli/"">萝莉</a><a href=""http://www.dilidili.com/zhenren/"">真人</a><a href=""http://www.dilidili.com/zhuangbi/"">装逼</a><a href=""http://www.dilidili.com/youxi/"">游戏</a><a href=""http://www.dilidili.com/roufan/"">肉番</a><a href=""http://www.dilidili.com/tuili/"">推理</a><a href=""http://www.dilidili.com/qingchun/"">青春</a><a href=""http://www.dilidili.com/kongbu/"">恐怖</a><a href=""http://www.dilidili.com/jizhan/"">机战</a><a href=""http://www.dilidili.com/rexue/"">热血</a><a href=""http://www.dilidili.com/maoxian/"">冒险</a><a href=""http://www.dilidili.com/hougong/"">后宫</a><a href=""http://www.dilidili.com/qihuan/"">奇幻</a><a href=""http://www.dilidili.com/tongnian/"">童年</a></dd>";
            foreach (Match item in Regex.Matches(a, @"<a href=""(.*?)"">(.*?)</a>"))
            {
                list_Type.Add(new CbTypeModel() {
                    Info = item.Groups[1].Value,
                    Name = item.Groups[2].Value
                });
            }
            list_Type.Add(new CbTypeModel() { Name = "轻小说", Info = "http://www.dilidili.com/"+Uri.EscapeDataString("轻小说") +"/" });
            list_Type.Add(new CbTypeModel() { Name= "日剧专区",Info= "http://www.dilidili.com/anime/riju/" });
            cb_Type.ItemsSource = list_Type;
            cb_Date.SelectedIndex = 3;
        }

        private void btn_Home_Click(object sender, RoutedEventArgs e)
        {
            //(sender as Button).BorderBrush = new SolidColorBrush(new Windows.UI.Color() { A=255,B=216,G=123,R=30});
            if (Convert.ToInt32((sender as Button).Tag) == pivot.SelectedIndex)
            {
                switch (Convert.ToInt32((sender as Button).Tag))
                {
                    case 0:
                        GetDiliHome();
                        break;
                    case 1:
                        TypeLoad();
                        break;
                    case 2:
                        break;
                    default:
                        break;
                }
            }
            else
            {
                pivot.SelectedIndex = Convert.ToInt32((sender as Button).Tag);
            }
          

        }

        private void UpdateUI()
        {
            SolidColorBrush color = new SolidColorBrush(new Windows.UI.Color() { A = 0, B = 0, G = 0, R = 0 });
            btn_Home.BorderBrush = color;
            btn_Seach.BorderBrush = color;
            btn_Tag.BorderBrush = color;
        }

        private void pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            UpdateUI();
            SolidColorBrush color = new SolidColorBrush(new Windows.UI.Color() { A = 255, B = 216, G = 123, R = 30 });
            switch (pivot.SelectedIndex)
            {
                case 0:
                    btn_Home.BorderBrush = color;
                    break;
                case 1:
                    btn_Tag.BorderBrush = color;
                    break;
                case 2:
                    btn_Seach.BorderBrush = color;
                    break;
                default:
                    break;
            }
        }

        private  void list_Home_ItemClick(object sender, ItemClickEventArgs e)
        {
            PageChnageEvent(BangumiType.Dilidili, (e.ClickedItem as DiliModel).url);
            //WebClientClass wc = new WebClientClass();
            //string results=await wc.GetResultsUTF8Encode(new Uri("http://www.dilidili.com/"));
        }
        WebClientClass wc;
        private async void GetDiliHome()
        {
            try
            {
                pr_Load.Visibility = Visibility.Visible;
                wc = new WebClientClass();
                string results = await wc.GetResultsUTF8Encode(new Uri("http://m.dilidili.com/"));
                MatchCollection mc = Regex.Matches(results, @" <li> <a href=""(.*?)"" title=""(.*?)""><img src=""(.*?)"".*?/>", RegexOptions.Singleline);
                List<DiliModel> listModel = new List<DiliModel>();
                if (mc.Count!=0)
                {
                    int[] nums = new int[30];
                    for (int i = 0; i < 30; i++)
                    {
                        while (true)
                        {
                            int ha = new Random().Next(0, mc.Count);
                            if (!nums.Contains(ha))
                            {
                                nums[i] = ha;
                                listModel.Add(new DiliModel()
                                {
                                    url = mc[ha].Groups[1].Value,
                                    title = mc[ha].Groups[2].Value,
                                    img = mc[ha].Groups[3].Value
                                });
                                break;
                            }
                        }
                    }
                   
                }
                list_Video.ItemsSource = listModel;
            }
            catch (Exception)
            {
                messShow.Show("读取失败", 3000);
            }
            finally
            {
                pr_Load.Visibility = Visibility.Collapsed;
            }

        }

        private void Page_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            int i = Convert.ToInt32(this.ActualWidth / 100);
            ViewBox_num.Width = this.ActualWidth / i - 11;
        }

        private  void seach_box_QuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)
        {
         
            //web_Seach.Navigate();
            //HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, new Uri("http://zhannei.baidu.com/cse/search?s=10158584941307875966&kwtype=0&q=" + Uri.EscapeDataString(seach_box.Text) + "&button=" + Uri.EscapeDataString("搜索") + "&ie=utf8&src=zz&site=www.dilidili.com&rg=1&wt=1&ht=1&pn=10&fpos=2&rmem=0")); // 此测试 aspx 在 WebServer 项目中

            // 构造 post 数据（无法 form 提交，因为试了很久，无法将 ContentType 设置为 "application/x-www-form-urlencoded"）
            //httpRequestMessage.Content = new HttpStringContent("hello webabcd");
            // 构造 http header 数据
            //httpRequestMessage.Headers.Append("user-agent", "Mozilla/5.0 (Linux; Android 5.0; SM-N9100 Build/LRX21V) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/37.0.0.0 Mobile Safari/537.36 MicroMessenger/6.0.2.56_r958800.520 NetType/WIFI");

            // NavigateWithHttpRequestMessage() - 通过 POST 请求和 HTTP 头加载 url
            // web_Seach.NavigateWithHttpRequestMessage(httpRequestMessage);
             pageNum = 1;
             maxretnum = 1;
            list_Seach.Items.Clear();
            GetSeachResults();
        }

        int pageNum = 1;
        int maxretnum = 1;
        private async void GetSeachResults()
        {
            if (pageNum> maxretnum)
            {
                return;
            }
            try
            {
                pr_Load.Visibility = Visibility.Visible;
                Loadings = true;
                wc = new WebClientClass();
                string url = "http://zhannei.baidu.com/api/customsearch/searchwap?q=" + Uri.EscapeDataString(seach_box.Text) + "&p=" + pageNum + "&s=10158584941307875966";
                string results = await wc.GetResults(new Uri(url));
                results = results.Replace("abstract", "Abstract");
                //<em><\/em> 
                DiliSerch model = JsonConvert.DeserializeObject<DiliSerch>(results);
                maxretnum = model.maxretnum;
                if (model.psstatus == "OK")
                {
                    List<DiliSerch> list = JsonConvert.DeserializeObject<List<DiliSerch>>(model.results.ToString());
                    list.ForEach(x => list_Seach.Items.Add(x));
                    pageNum++;
                }
                else
                {
                    messShow.Show("搜索失败！"+ model.psstatus, 3000);
                }
            }
            catch (Exception)
            {
                messShow.Show("搜索失败！",3000);
            }
            finally
            {
                Loadings = false;
                pr_Load.Visibility = Visibility.Collapsed;
            }
        }
        bool Loadings = false;
        private void sv_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
        {
            if (sv.VerticalOffset == sv.ScrollableHeight)
            {
                if (!Loadings)
                {

                    GetSeachResults();
                }
            }

        }

        private void list_Seach_ItemClick(object sender, ItemClickEventArgs e)
        {
            DiliSerch model = e.ClickedItem as DiliSerch;
            string a = Regex.Match(model.url+"/", "http://www.dilidili.com/anime/(.*?)/").Groups[0].Value;
            if (a.Length!=0)
            {
                PageChnageEvent(BangumiType.Dilidili, model.url);
                return;
            }
            string b = Regex.Match(model.url + "/", "http://www.dilidili.com/watch/(.*?)/").Groups[0].Value;
            if (b.Length != 0)
            {
                PlayEvent(BangumiType.Dilidili, model.url);
                return;
            }
            messShow.Show("Sorry,不支持此类型链接的跳转",3000);
        }

        private async void GetListInfo(string url)
        {
            try
            {
                pr_Load.Visibility = Visibility.Visible;
                wc = new WebClientClass();
                //string url = string.Format("http://www.dilidili.com/anime/{0}/", date);
                string results = await wc.GetResultsUTF8Encode(new Uri(url));
                MatchCollection mc = Regex.Matches(results, @"<dl>.*?<dt><a hrel=""(.*?)""><img src=""(.*?)""/></a></dt>.*?<dd>.*?<h3><a href=""(.*?)"">(.*?)</a></h3>.*?<p><div class=""d_label""><b>地区：</b>(.*?)</div><div class=""d_label""><b>年代：</b>(.*?)</div></p>.*?<p><div class=""d_label""><b>标签：</b>(.*?)</div><div class=""d_label""><b>播放：</b>(.*?)</div></p>.*?<p><b>看点：</b>(.*?)</p>.*?<p><b>简介：</b>(.*?)</p>.*?<p><b style=""color:#F00"">状态:</b>(.*?)</p>.*?</dd>.*?</dl>", RegexOptions.Singleline);
                if (mc.Count==0)
                {
                    mc = Regex.Matches(results, @"<dl>.*?<dt><a href=""(.*?)""><img src=""(.*?)""/></a></dt>.*?<dd>.*?<h3><a href=""(.*?)"">(.*?)</a></h3>.*?<p><div class=""d_label""><b>地区：</b>(.*?)</div><div class=""d_label""><b>年代：</b>(.*?)</div></p>.*?<p><div class=""d_label""><b>标签：</b>(.*?)</div><div class=""d_label""><b>播放：</b>(.*?)</div></p>.*?<p><b>看点：</b>(.*?)</p>.*?<p><b>简介：</b>(.*?)</p>.*?<p><b style=""color:#F00"">状态:</b>(.*?)</p>.*?</dd>.*?</dl>", RegexOptions.Singleline);
                }
                List <DiliModel> listModel = new List<DiliModel>();
                foreach (Match item in mc)
                {
                    listModel.Add(new DiliModel()
                    {
                        url = item.Groups[1].Value,
                        title = item.Groups[4].Value,
                        date = item.Groups[6].Value,
                        area = item.Groups[5].Value,
                        tag = item.Groups[7].Value,
                        shortDesc = item.Groups[9].Value,
                        desc = item.Groups[10].Value,
                        img = item.Groups[2].Value
                    });
                }
                list_Info.ItemsSource = listModel;
            }
            catch (Exception)
            {
                messShow.Show("读取失败", 3000);
            }
            finally
            {
                pr_Load.Visibility = Visibility.Collapsed;
            }

        }

        private void cb_Date_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cb_Date.SelectedIndex!=-1)
            {
                cb_Area.SelectedIndex = -1;
                cb_Type.SelectedIndex = -1;
                GetListInfo((cb_Date.SelectedItem as CbTypeModel).Info);
            }
        }

        private void list_Info_ItemClick(object sender, ItemClickEventArgs e)
        {

            Uri mc;
            if (!Uri.TryCreate((e.ClickedItem as DiliModel).url, UriKind.Absolute,out mc))
            {
                PageChnageEvent(BangumiType.Dilidili, "http://www.dilidili.com/" + (e.ClickedItem as DiliModel).url);
            }
            else
            {
                PageChnageEvent(BangumiType.Dilidili,  (e.ClickedItem as DiliModel).url);
            }
        }

        private void cb_Area_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cb_Area.SelectedIndex != -1)
            {
                cb_Date.SelectedIndex = -1;
                cb_Type.SelectedIndex = -1;
                GetListInfo((cb_Area.SelectedItem as CbTypeModel).Info);
            }
        }

        private void cb_Type_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cb_Type.SelectedIndex != -1)
            {
                cb_Date.SelectedIndex = -1;
                cb_Area.SelectedIndex = -1;
                CbTypeModel a= cb_Type.SelectedItem as CbTypeModel;
                GetListInfo((cb_Type.SelectedItem as CbTypeModel).Info);
            }
        }
    }

    public class DiliModel
    {
        public string url { get; set; }
        public string title { get; set; }
        public string img { get; set; }

        public string date { get; set; }
        public string area { get; set; }
        public string tag { get; set; }
        public string desc { get; set; }
        public string shortDesc { get; set; }
    }
    public class CbTypeModel
    {
        public string Name { get; set; }
        public string Info { get; set; }
    }
    public class DiliSerch
    {
        public string psstatus { get; set; }
        public int maxretnum { get; set; }

        public object results { get; set; }
        public string url { get; set; }
        public string title { get; set; }
        public string Title
        {
            get { return HtmlHelper.HtmlDecode(title); }
        }
        public string Abstract { get; set; }//系统关键字，需转换
        public string AAbstract
        {
            get { return HtmlHelper.HtmlDecode(Abstract); }
        }
        public string lastModified { get; set; }
    }
}
